package com.mrroman.linksender.passdb;
import java.net.PasswordAuthentication;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.logging.Logger;

import com.mrroman.linksender.gui.PasswordDialog;
import com.mrroman.linksender.ioc.In;
import com.mrroman.linksender.ioc.Init;
import com.mrroman.linksender.ioc.Locales;
import com.mrroman.linksender.ioc.Log;
import com.mrroman.linksender.ioc.Name;

@Name("linksender.PasswordKeeper")
public class PasswordKeeper {

	private Map<String, PasswordAuthentication> passwordDB;
	
	@Log
	private Logger logger;
	
	@Locales
	private ResourceBundle messages;
	
	@In(impl = FilePasswordStorage.class)
	private PasswordStorage passwordStorage;
	
	@In(impl = PasswordDialog.class)
	private PasswordEditor passwordEditor;
	
	@Init
	public void init() {
		passwordDB = passwordStorage.readDatabase();
	}
	
	public void setPasswordEditor(PasswordEditor passwordEditor) {
		this.passwordEditor = passwordEditor;
	}
	
	public PasswordAuthentication getPassword(String requestingHost) {
		PasswordAuthentication pa = passwordDB.get(requestingHost);
		
		if (pa == null) {
			pa = showPasswordDialog(requestingHost);
			
			if (pa != null) 
				storePassword(requestingHost, pa);
		}
		
		return pa;
	}

	private PasswordAuthentication showPasswordDialog(String requestingHost) {
		if (passwordEditor != null)
			return passwordEditor.getPassword(requestingHost, "");
		else
			return null;
	}

	private void storePassword(String requestingHost, PasswordAuthentication pa) {
		passwordDB.put(requestingHost, pa);
		passwordStorage.writeDatabase(passwordDB);
	}

}
